── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks plotly::filter(), stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(nycflights13)library(data.table)
Attaching package: 'data.table'
The following objects are masked from 'package:lubridate':
hour, isoweek, mday, minute, month, quarter, second, wday, week,
yday, year
The following objects are masked from 'package:dplyr':
between, first, last
The following object is masked from 'package:purrr':
transpose
library(dplyr)
1
a
#inspired from chatgpt# Define GCD and LCM in RcppRcpp::cppFunction('int gcd(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return abs(a);}int lcm(int a, int b) { return abs(a * b) / gcd(a, b);}')
setClass("rational",slots =c(a ="numeric",b ="numeric"))#Validity the numerator and denominatorsetValidity("rational", function(object) {if (object@b ==0) stop("denominator is zero")if(object@b%%1!=0|object@a%%1!=0) stop("numerator and denominator all need to be integer")return(TRUE)})
Class "rational" [in ".GlobalEnv"]
Slots:
Name: a b
Class: numeric numeric
setMethod("quotient", "rational", function(object, digits =7) {if(!is.numeric(digits)) stop("digits need to be an integer")if(digits%%1!=0)stop("digits need to be an integer, not a double") res <- object@a / object@bprint(round(res, digits))return(round(res, digits))})#add and minus , same modesetMethod("+", signature(e1 ="rational",e2 ="rational"),function(e1, e2) { res_a=e1@a*e2@b+e1@b*e2@a res_b=e1@b*e2@breturn(simplify(new("rational",a=res_a,b=res_b))) })setMethod("-", signature(e1 ="rational",e2 ="rational"),function(e1, e2) {return(e1+new("rational",a=-e2@a,b=e2@b)) })#times and division,set a validation in divisionsetMethod("*", signature(e1 ="rational",e2 ="rational"),function(e1, e2) { res_a=e1@a*e2@a res_b=e1@b*e2@breturn(simplify(new("rational",a=res_a,b=res_b))) })setMethod("/", signature(e1 ="rational",e2 ="rational"),function(e1, e2) { res_a=e1@a*e2@b res_b=e1@b*e2@aif(res_b==0)stop("result denominator is zero")return(simplify(new("rational",a=res_a,b=res_b))) })
Error in quotient(r2, digits = 3.14): digits need to be an integer, not a double
quotient(r2, digits ="avocado")
Error in quotient(r2, digits = "avocado"): digits need to be an integer
q2 <-quotient(r2, digits =3)
[1] 0.03
q2
[1] 0.03
quotient(r3)
[1] 0
[1] 0
simplify(r1)
[1] "4 / 1"
simplify(r2)
[1] "7 / 230"
simplify(r3)
[1] "0 / 1"
c
#test the denominator = zerotest1<-new("rational",a=24,b=0)
Error in validityMethod(object): denominator is zero
2
a
We retrieve the solution code from ps4.
#code from last solution given by teacherart=read.csv("df_for_ml_improved_new_market.csv")art$Genre___Others[art$Genre___Painting ==1] <-0art$genre <-"Photography"art$genre[art$Genre___Print ==1] <-"Print"art$genre[art$Genre___Sculpture ==1] <-"Sculpture"art$genre[art$Genre___Painting ==1] <-"Painting"art$genre[art$Genre___Others ==1] <-"Other"yeargenre <-with(art, table(year, genre))yearge<-data.frame(yeargenre)
We use plotly here:
p <-plot_ly(yearge, x =~ year, y =~ Freq,color =~genre,type ="scatter", mode ="lines")%>%layout(title ='Frequency of Genre each year',plot_bgcolor ="#e5ecf6", yaxis =list(title ='frequency'))p
b
We use the code from ps4 solution
artmedian <-aggregate(art$price_usd, by =list(art$year, art$genre),FUN = median, na.rm =TRUE)names(artmedian) <-c("year", "genre", "price_usd_median")artmedianall <-aggregate(art$price_usd, by =list(art$year),FUN = median, na.rm =TRUE)names(artmedianall) <-c("year", "price_usd_median")artmedianall$genre<-"All"#combine two dataset to use plotly easierartmedian<-rbind(artmedianall,artmedian)
#get from chatgpt and discussed with friendsp1 <-plot_ly(x =~year, y =~price_usd_median,color =~genre,type ='scatter',mode ='lines+markers',data=artmedian,text =~paste("Genre:", genre, "<br>Year:", year, "<br>Avg Price (USD):", price_usd_median))%>%layout(title ="Change in Sales Price Over Time (Overall and By Genre)",xaxis =list(title ="Year"),yaxis =list(title ="Average Sales Price (USD)"),updatemenus =list(list(type ="dropdown",active =0,buttons =list(list(label ="show both",method ="update",args =list(list(visible =c(rep(TRUE, n_distinct(artmedian$genre) ))),list(title ="Median Sales Price Over Time (Overall and Genre)"))),list(label ="All",method ="update",args =list(list(visible =c(TRUE, rep(FALSE, n_distinct(artmedian$genre) -1))),list(title ="Median Sales Price Over Time Overall)"))),list(label ="By Genre",method ="update",args =list(list(visible =c(FALSE, rep(TRUE, n_distinct(artmedian$genre) -1))),list(title ="Median Sales Price Over Time By Genre"))) ) ) ) )p1
3
a
#change to data tablefl<-as.data.frame(flights)setDT(fl)ap<-as.data.frame(airports)setDT(ap)fl[,.(mean_delay =mean(dep_delay, na.rm =TRUE),med_delay =median(dep_delay, na.rm =TRUE),numflights = .N),by=origin ][numflights >=10 ][ap, on = .(origin = faa) ][!is.na(mean_delay) ][, .(name, mean_delay, med_delay) ][order(-mean_delay) ]
name mean_delay med_delay
<char> <num> <num>
1: Newark Liberty Intl 15.10795 -1
2: John F Kennedy Intl 12.11216 -1
3: La Guardia 10.34688 -3